#include <stdio.h>
#include <string.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_log.h"
#include "iot_main.h"
#include "iot_profile.h"

#include "wifi_connect.h"
#include "wifi_config.h"
#include "aht20.h"
#include "led.h"
#include "mq2.h"

#define ONE_SECOND (1000)
/* oc request id */
#define CN_COMMAND_INDEX "commands/request_id="
#define WECHAT_SUBSCRIBE_LIGHT "light"
#define WECHAT_SUBSCRIBE_LIGHT_ON_STATE "1"
#define WECHAT_SUBSCRIBE_LIGHT_OFF_STATE "0"

int g_lightStatus = -1;

typedef struct FunctionCallback
{
    hi_bool stop;
    hi_u32 conLost;
    hi_u32 queueID;
    hi_u32 iotTaskID;
} FunctionCallback;
FunctionCallback g_functionCallback;

// < this is the callback function, set to the mqtt, and if any messages come, it will be called
// < The payload here is the json string
static void DemoMsgRcvCallBack(int qos, const char *topic, const char *payload)
{
    IOT_LOG_DEBUG("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
    /* 云端下发命令后，板端的操作处理 */
    if (strstr(payload, WECHAT_SUBSCRIBE_LIGHT) != NULL)
    {
        if (strstr(payload, WECHAT_SUBSCRIBE_LIGHT_OFF_STATE) != NULL)
        {
            Led_Off();
            g_lightStatus = HI_FALSE;
        }
        else
        {
            Led_On();
            g_lightStatus = HI_TRUE;
        }
    }
    return HI_NULL;
}

/* publish sample */
hi_void IotPublishSample(void)
{
    float humidity = 0.0f;
    float temperature = 0.0f;
    float luminance = 0.0f;
    double ppm = 0.0;

    AHT20_GetMeasureResult(&temperature, &humidity);
    MQ2_GetData(&ppm);
    RES_GetData(&luminance);

    /* reported attribute */
    WeChatProfile weChatProfile = {
        .subscribeType = "type",
        .status.subState = "state",
        .status.subReport = "reported",
        .status.reportVersion = "version",
        .status.Token = "clientToken",
        /* report motor */
        .reportAction.subDeviceActionMotor = "motor",
        .reportAction.motorActionStatus = 0, /* 0 : motor off */
        /* report temperature */
        .reportAction.subDeviceActionTemperature = "temperature",
        .reportAction.temperatureData = temperature, /* 30 :temperature data */
        /* report humidity */
        .reportAction.subDeviceActionHumidity = "humidity",
        .reportAction.humidityActionData = humidity, /* humidity data */
        /* report light_intensity */
        .reportAction.subDeviceActionLightIntensity = "light_intensity",
        .reportAction.lightIntensityActionData = luminance, /* 60 : light_intensity */
        /* report light_intensity */
        .reportAction.subDeviceActionppm = "ppm",
        .reportAction.ppmActionData = ppm, /* 60 : light_intensity */
    };

    /* report light */
    if (g_lightStatus == HI_TRUE)
    {
        weChatProfile.reportAction.subDeviceActionLight = "light";
        weChatProfile.reportAction.lightActionStatus = 1; /* 1: light on */
    }
    else if (g_lightStatus == HI_FALSE)
    {
        weChatProfile.reportAction.subDeviceActionLight = "light";
        weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
    }
    else
    {
        weChatProfile.reportAction.subDeviceActionLight = "light";
        weChatProfile.reportAction.lightActionStatus = 0; /* 0: light off */
    }
    /* profile report */
    IoTProfilePropertyReport(CONFIG_USER_ID, &weChatProfile);
}

// < this is the demo main task entry,here we will set the wifi/cjson/mqtt ready and
// < wait if any work to do in the while
static hi_void *IotCloudEntry(const char *arg)
{
    WifiConnect();
    cJsonInit();
    IoTMain();
    /* 云端下发回调 */
    IoTSetMsgCallback(DemoMsgRcvCallBack);
    /* 主动上报 */
    while (1)
    {
        /* 用户可以在这调用发布函数进行发布，需要用户自己写调用函数 */
        IotPublishSample(); // 发布例程
        TaskMsleep(ONE_SECOND);
    }
    return NULL;
}

// < This is the demo entry, we create a task here,
// and all the works has been done in the demo_entry
#define CN_IOT_TASK_STACKSIZE 0x1000
#define CN_IOT_TASK_PRIOR 25
#define CN_IOT_TASK_NAME "IOTDCLOUD"

static void IotCloud(void)
{
    osThreadAttr_t attr;

    attr.name = "IOTCLOUD";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = CN_IOT_TASK_STACKSIZE;
    attr.priority = CN_IOT_TASK_PRIOR;

    if (osThreadNew((osThreadFunc_t)IotCloudEntry, NULL, &attr) == NULL)
    {
        printf("[mqtt] Failed to create IOTCLOUD!\n");
    }
}

SYS_RUN(IotCloud);